package com.hainiu.cat.web.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * create by biji.zhao on 2021/6/4
 */
@Configuration
public class TopicRabbitConfig {
    /**
     * 给topic队列起名
     */
    public final static String TOPIC_FIRST_QUEUE = "topic.first";
    public final static String TOPIC_SECOND_QUEUE = "topic.second";

    /**
     * 给交换机起名
     */
    public final static String TOPIC_EXCHANGE= "topicExchange";

    /**
     * 规定topic队列的routing-key
     */
    public final static String TOPIC_FIRST_ROUTING_KEY = "topic.red";
    public final static String TOPIC_SECOND_ROUTING_KEY = "topic.yellow";
    public final static String TOPIC_SPECIAL_ROUTING_KEY = "topic.#";

    @Bean
    public Queue firstQueue() {
        return new Queue(TopicRabbitConfig.TOPIC_FIRST_QUEUE);
    }

    @Bean
    public Queue secondQueue() {
        return new Queue(TopicRabbitConfig.TOPIC_SECOND_QUEUE);
    }//这里面的参数就是给队列起个名字

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(TOPIC_EXCHANGE);
    }

    /**
     * 将firstQueue和topicExchange绑定,而且绑定的键值为topic.red
     * 这样只要是消息携带的路由键是topic.red,才会分发到该队列
     * @return 绑定结果
     */
    @Bean
    Binding bindingExchangeMessage() {
        return BindingBuilder.bind(firstQueue()).to(exchange()).with(TOPIC_FIRST_ROUTING_KEY);
    }

    /**
     * 将secondQueue (topic.second)  和exchange (topicExchange)绑定,而且绑定的键值为用上通配路由键规则topic.#
     * 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列
     * @return 绑定结果
     */
    @Bean
    Binding bindingExchangeMessage2() {
        // 绑定队列和交换机   并知道路由key
        return BindingBuilder.bind(secondQueue()).to(exchange()).with(TOPIC_SPECIAL_ROUTING_KEY);
    }
}
